<template>
	<view>
		<view class="uploadContent">
			<view class="title">点击选择图片</view>
			<view class="uploadBox">
				<u-upload :fileList="fileList1" @afterRead="afterRead" @delete="deletePic" name="1" multiple
					:maxCount="9"></u-upload>
			</view>
			<view class="inputBox">
				<u--textarea placeholder="请输入留言内容" v-model="desc" border="surround" autoHeight></u--textarea>
			</view>
			<u-button type="primary" :hairline="false" @click="btnSub" customStyle="margin-top: 15px">发表</u-button>
		</view>
	</view>
</template>

<script>
	import Upyun from '@/utills/upyun-wxapp-sdk.js'
	import request from '@/utills/request.js'
	export default {
		data() {
			return {
				fileList1: [],
				desc: ''
			}
		},
		onLoad() {

		},
		methods: {
			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1)
			},
			// 新增图片
			async afterRead(event) {
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList${event.name}`].length
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
					})
				})
			},
			btnSub() {
				const upyun = new Upyun({
					bucket: 'cloudreve-zzk',
					operator: 'qq769522974',
					//又拍云获取signature签名接口
					getSignatureUrl: this.baseurl + 'getSignatureUrl/get'
				})
				console.log(this.fileList1);
				const imgUrl = [];
				const promissArr = [];
				var uploadUrl = "https://cloud.iava.top";
				for (let i = 0; i < this.fileList1.length; i++) {
					let suffix = /\.[^\.]+$/.exec(this.fileList1[0].url)[0]; // 正则表达式，获取文件扩展名
					promissArr.push(new Promise((reslove, reject) => {
						upyun.upload({
							localPath: this.fileList1[i].url,
							remotePath: '/easyNoteImg/' + new Date().getTime() + suffix,
							success: res => {
								// console.log("上传成功" + res.data);
								var url = uploadUrl + JSON.parse(res.data).url;
								console.log(url);
								imgUrl.push(url);
								reslove(res);
							},
							fail: (err) => {
								reject(err)
							}
						})
					}))
				}
				Promise.all(promissArr).then(res => {
					console.log(imgUrl);
					// console.log("promiss");
					uni.request({
						method: 'POST',
						url: this.baseurl + 'msg/release',
						header: {
							"Content-Type": "application/x-www-form-urlencoded;charset=utf-8",
							"token": uni.getStorageSync('token')
						},
						data: {
							desc: this.desc,
							img: imgUrl
						},
						success: res => {
							console.log(res);
							//清空
							this.fileList1 = [];
							this.desc = '';
							uni.$u.toast('发布成功');
							uni.navigateBack()
						}
					})
				})
			}
		}
	}
</script>

<style>
	.uploadContent {
		padding: 20px;
	}

	.uploadBox {
		margin-top: 20px;
	}

	.inputBox {
		border: 1px solid #e8e8e8;
		border-radius: 8px;
		margin-top: 15px;
	}
</style>
